#include<iostream>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<unistd.h>
using namespace std;
const int defaulter = -1;
const int gsize = 4096;
const int proj = 0x66;
string pathname = ".";

#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)
    

class Shm_Oper{

public:
    Shm_Oper()
    :_shmid(defaulter)
    ,_size(gsize)
    {}
    void Creat()
    {
        key_t n = ftok(pathname.c_str(),proj);
        if(n<0)
        {
            ERR_EXIT("ftok");
        }
        cout<<"creat key success!"<<endl;
        _shmid = shmget(n,_size,IPC_CREAT|IPC_EXCL);
        if(_shmid<0)
        {
            ERR_EXIT("shmget");
        }
        cout<<"creat sys success"<<endl;
        printf("shmid = %d\n",_shmid);
    }
    void destroy()
    {
        if(_shmid==-1)
        {
            return;
        }
        int n = shmctl(_shmid,IPC_RMID,nullptr);
        if(n>0)
        {
            printf("sys delete success shmid = %d\n",_shmid);
        }
        ERR_EXIT("shmctl");
    }

    ~Shm_Oper(){}

private:
    int _shmid;
    int _size;
};